package server.server02;

import server.server02.xml.WebContext;
import server.server02.xml.webHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class WebApp {
    private static WebContext context;
    static {
        try {
//SAX解析
            //1、获取解析工厂
            SAXParserFactory factory=SAXParserFactory.newInstance();
            //2、从解析工厂获取解析器
            SAXParser parse =factory.newSAXParser();
            //3、编写处理器
            //4、加载文档 Document 注册处理器
            webHandler handler=new webHandler();
            //5、解析
            parse.parse(Thread.currentThread().getContextClassLoader()
                            .getResourceAsStream("server/server02/xml/web.xml")
                    ,handler);
            //获取数据
            context = new WebContext(handler.getEntitys(),handler.getMappings());
        }catch (Exception e){
            System.out.println("解析配置文件错误");
        }
    }

    /**
     * 通过url获取配置文件的servlet
     * @param url
     * @return
     */
    public static Servlet getServletFromeUrl(String url){
    //假设请求的是/login
    String className = context.GetClz("/"+url);
    //反射
    Class clz = null;
    try {
        clz = Class.forName(className);
        Servlet servlet = (Servlet)clz.newInstance();
        return servlet;
    } catch (Exception e) {
        e.printStackTrace();
    }
   return null;
}
}
